<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React - Promise</title>
    <script src="../build/react.js"></script>
    <script src="../build/react-dom.js"></script>
    <script src="../build/browser.min.js"></script>
    <script src="../build/jquery-1.10.1.min.js"></script>
</head>
<body>
    <div id="container"></div>
    <script type="text/babel">
        var RepoList = React.createClass({
            getInitialState: function(){
                return {
                    loading: true,
                    error: null,
                    data: null
                }

            },
            componentDidMount: function(){
                this.props.promise.then(
                        value => this.setState({loading:false, data: value}),
                        error => this.setState({loading: false, error: error})
                );
            },
            render: function(){
                if(this.state.loading){
                    return <span>loading...</span>;
                }else if(this.state.error !== null){
                    return <span>Error: {this.state.error.message}</span>;
                }else{
                    var repos = this.state.data.items;
                    var repoList = repos.map(function(repo, index){
                        return (
                                <li key={index}>
                                    <a href={repo.html_url}>{repo.name} <br/> {repo.description}</a>
                                </li>
                        );
                    });
                    return (
                            <main>
                                <h1>Most Popular Javascript Projects Github</h1>
                                <ol>{repoList}</ol>
                            </main>
                    )
                }
            }
        })
        ReactDOM.render(
                <RepoList promise={$.getJSON("https://api.github.com/search/repositories?q=javascript&sort=stars")}/>,
        document.getElementById("container")
        )
    </script>

</body>
</html>